package _18_剑指OfferII;

import java.util.*;

public class _035_剑指OfferII最小时间差 {

    private static final int HALF_INTERVAL = 12 * 60;

    public static void main(String[] args) {
        _035_剑指OfferII最小时间差 v = new _035_剑指OfferII最小时间差();

        List<String> lists = new ArrayList<>();
        lists.add("23:59");
        lists.add("00:00");
        lists.add("00:00");

        System.out.println(v.findMinDifference(lists));
    }

    public int findMinDifference(List<String> timePoints) {
        if (timePoints.size() > (HALF_INTERVAL << 1)) return 0;
        // 字符串排序
        timePoints.sort(Comparator.naturalOrder());
        int len = timePoints.size();
        int ans = HALF_INTERVAL << 1;
        for (int i = 1; i < len; i++) {
            ans = Math.min(ans, getInterval(timePoints.get(i - 1), timePoints.get(i)));
        }
        // 首位计算
        ans = Math.min(ans, getInterval(timePoints.get(0), timePoints.get(len - 1)));
        return ans;
    }

    public int getInterval(String time1, String time2) {
        String[] split1 = time1.split(":");
        String[] split2 = time2.split(":");
        // 小时间隔
        int hourInterval = Integer.parseInt(split2[0]) - Integer.parseInt(split1[0]);
        // 分钟间隔
        int minuteInterval = Integer.parseInt(split2[1]) - Integer.parseInt(split1[1]);
        // 总间隔
        int totalInterval = hourInterval * 60 + minuteInterval;

        // 是否超过时间的一半
        if (totalInterval > HALF_INTERVAL) {
            return (HALF_INTERVAL << 1) - totalInterval;
        }
        return totalInterval;
    }

}
